<?php
// $Id: tcprofile_search.admin.inc,v 1.0 2010/08/18 12:48:18 llin Exp $

/**
 * Implementation of hook_admin_settings().
 */
function tcprofile_search_admin_settings() {
  // get profile fields
  $result = db_query("SELECT title, name, type FROM {profile_fields} ORDER BY category, weight");
  $options = array();
  while ($row = db_fetch_array($result)) {
    $options[$row['name']] = $row['title'];
  }

  // set these fields for general and advanced search
  $form['tcprofile_search_general_fields'] = array(
    '#type'          => 'checkboxes',
    '#title'         => t('Include these profile fields in the GENERAL profile search form'),
    '#options'       => $options,
    '#default_value' => variable_get('tcprofile_search_general_fields', array_keys($options)),
  );

  $form['tcprofile_search_advanced_fields'] = array(
    '#type'          => 'checkboxes',
    '#title'         => t('Include these profile fields in the ADVANCED profile search form'),
    '#options'       => $options,
    '#default_value' => variable_get('tcprofile_search_advanced_fields', array_keys($options)),
  );

  $form['tcprofile_search_access_denied_blurb'] = array(
    '#title' => t('Access Denied'),
    '#description' => t('Blurb for denying user access to this page'),
    '#type' => 'textarea',
    '#default_value' => variable_get('tcprofile_search_access_denied_blurb', ''),
  );

  $form['tcprofile_search_membership_upgrade_blurb'] = array(
    '#title' => t('Upgrade Membership'),
    '#description' => t('Blurb for teasing user to upgrade memebership'),
    '#type' => 'textarea',
    '#default_value' => variable_get('tcprofile_search_membership_upgrade_blurb', ''),
  );
  
  return system_settings_form($form);
}

/**
 * search user form / result
 *
 * @ingroup forms
 * @see tcprofile_search_user_search_submit
 */
function tcprofile_search_user_search($callback_arg = '') {
  $op = isset($_POST['op']) ? $_POST['op'] : $callback_arg;
  switch ($op) {
    default:
      $output = drupal_get_form('tcprofile_search_user_search_form');
      $output .= tcprofile_search_render_form(tcprofile_search_user_admin());

      if (isset($_POST['user_operations'])) { // actions
        // if no checkbox checked
        if (count($_POST['accounts']) == 0) {
          form_set_error('', t('No users selected.'));
          return $output;
        }
        else {
          if ($_POST['user_operations'] == 'delete') { // delete action go to confirm page
            return drupal_get_form('tcprofile_search_user_multiple_delete_confirm');
          }
          else { 
            if ($_POST['user_operations'] == 'delete_confirmed') {
              $_POST['user_operations'] = 'delete';

              foreach ($_POST['accounts'] as $uid => $value) {
                user_delete($_POST, $uid);
              }
              drupal_set_message(t('The users have been deleted.'));
            }

            $operation_rid = explode('-', $_POST['user_operations']);
            $operations = array();
            if ($operation_rid[0] == 'add_role' || $operation_rid[0] == 'remove_role') {
              $rid = $operation_rid[1];
              $operation['callback'] = 'user_multiple_role_edit';
              $operation['callback arguments'] = array($operation_rid[0], $rid); 
            }
            else {
              $operations = module_invoke_all('user_operations');
              $operation = $operations[$_POST['user_operations']];
            }
            // Filter out unchecked accounts.
            $accounts = array_filter($_POST['accounts']);
            if ($function = $operation['callback']) {
              // Add in callback arguments if present.
              if (isset($operation['callback arguments'])) {
                $args = array_merge(array($accounts), $operation['callback arguments']);
              }
              else {
                $args = array($accounts);
              }
              call_user_func_array($function, $args);

              drupal_set_message(t('The update has been performed with function: ' . $function));
            }
            return drupal_get_form('tcprofile_search_user_search_form') . tcprofile_search_render_form(tcprofile_search_user_admin()); 
          }
        }
      }
      else {
        return $output;
      }
  }

} // function tcprofile_search_user_search

/**
 * Return form for searching user
 *
 * @ingroup forms
 */
function tcprofile_search_user_search_form() {
  global $user;
  $form['search_filters'] = array(
    '#type' => 'fieldset',
    '#title' => t('Show only users where user name contains'),
  );
  $form['search_filters']['status']['name'] = array(
    '#type' => 'textfield',
    '#title' => '',
    '#default_value' => isset($_GET['name']) ? $_GET['name'] : '',
    '#rows' => 1,
    '#size' => 10,
  );
  $form['search_filters']['buttons']['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Search',
  );
  $form['#method'] = 'GET';
  drupal_add_js('misc/form.js', 'core');
  return $form;
} // function tcprofile_search_user_search_form

/**
 * submit action, before save the searched key in session
 * @param Array $form
 * @param Array $form_state
 */
function tcprofile_search_user_search_form_submit($form, &$form_state) {
  return;
} // function tcprofile_search_user_search_form_submit

/**
 * get searched results in form
 * @return Array $form
 */
function tcprofile_search_user_admin() {
  // get user name from url
  $username = isset($_GET['name']) ? $_GET['name'] : '';
  
  // compose query
  $sql = "SELECT DISTINCT u.uid, u.name, u.status, u.created, u.access FROM {users} u LEFT JOIN {users_roles} ur ON u.uid = ur.uid WHERE u.uid != 0 ";
  $query_count = "SELECT COUNT(DISTINCT u.uid) FROM {users} u LEFT JOIN {users_roles} ur ON u.uid = ur.uid WHERE u.uid != 0 ";
  $where = " AND UPPER(u.name) LIKE '%%%s%%'";
  // only one order: Member for, get sort=asc&order=Member+for
  $query_order = isset($_GET['sort']) ? $_GET['sort'] : 'desc';
  if (strtoupper($query_order) == 'DESC' || strtoupper($query_order) == 'ASC') {
    $query_order = ' ORDER BY u.created ' . strtoupper($query_order);
  }
  
  if (strlen($username) > 0 ) {
    $sql .= $where . $query_order;
    $query_count .= $where . $query_order;
  }

  $header = array(
    array(),
    array('data' => t('Username'), 'field' => 'u.name'),
    array('data' => t('Status'), 'field' => 'u.status'),
    t('Roles'),
    array('data' => t('Member for'), 'field' => 'u.created', 'sort' => 'desc'),
    array('data' => t('Last access'), 'field' => 'u.access'),
    t('Operations')
  );

  $sql .= tablesort_sql($header);

  $result = pager_query($sql, 50, 0, $query_count, array(strtoupper($username)));

  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('Update options'),
    '#prefix' => '<div class="container-inline">',
    '#suffix' => '</div>',
  );
  $options = array();
  foreach (module_invoke_all('user_operations') as $operation => $array) {
    $options[$operation] = $array['label'];
  }
  $form['options']['operation'] = array(
    '#type' => 'select',
    '#name' => 'user_operations',
    '#options' => $options,
    '#default_value' => 'unblock',
  );
  $form['options']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
  );

  $destination = drupal_get_destination();

  $status = array(t('blocked'), t('active'));
  $roles = user_roles(TRUE);
  $accounts = array();
  $form['accounts'] = array(
    '#type' => 'checkboxes',
  );

  while ($account = db_fetch_object($result)) {
    $accounts[$account->uid] = '';
    $form['accounts'][$account->uid] = array('#type' => 'checkbox', '#return_value' => $account->uid, '#parents' => array('accounts', $account->uid), '#array_parents' => array('accounts', $account->uid), '#process' => array('form_expand_ahah'), '#name' => 'accounts[' . $account->uid . ']', '#id' => 'edit-accounts-' . $account->uid);
    $form['name'][$account->uid] = array('#value' => theme('username', $account));
    $form['status'][$account->uid] =  array('#value' => $status[$account->status]);
    $users_roles = array();
    $roles_result = db_query('SELECT rid FROM {users_roles} WHERE uid = %d', $account->uid);
    while ($user_role = db_fetch_object($roles_result)) {
      $users_roles[] = $roles[$user_role->rid];
    }
    asort($users_roles);
    $form['roles'][$account->uid][0] = array('#value' => theme('item_list', $users_roles));
    $form['member_for'][$account->uid] = array('#value' => format_interval(time() - $account->created));
    $form['last_access'][$account->uid] =  array('#value' => $account->access ? t('@time ago', array('@time' => format_interval(time() - $account->access))) : t('never'));
    $form['operations'][$account->uid] = array('#value' => l(t('edit'), "user/$account->uid/edit", array('query' => $destination)));
  }
  $form['accounts']['#options'] = $accounts;
  $form['pager'] = array('#value' => theme('pager', NULL, 50, 0));

  return $form;
} // function tcprofile_search_user_admin

/**
 * Theme user search overview.
 *
 */
function tcprofile_search_render_form($form) {
  // Overview table:
  $header = array(
    theme('table_select_header_cell'),
    array('data' => t('Username'), 'field' => 'u.name'),
    array('data' => t('Status'), 'field' => 'u.status'),
    t('Roles'),
    array('data' => t('Member for'), 'field' => 'u.created', 'sort' => 'desc'),
    array('data' => t('Last access'), 'field' => 'u.access'),
    t('Operations')
  );

  $output = drupal_render($form['options']);
  if (isset($form['name']) && is_array($form['name'])) {
    foreach (element_children($form['name']) as $key) {
      $rows[] = array(
        drupal_render($form['accounts'][$key]),
        drupal_render($form['name'][$key]),
        drupal_render($form['status'][$key]),
        drupal_render($form['roles'][$key]),
        drupal_render($form['member_for'][$key]),
        drupal_render($form['last_access'][$key]),
        drupal_render($form['operations'][$key]),
      );
    }
  }
  else {
    $rows[] = array(array('data' => t('No users available.'), 'colspan' => '7'));
  }

  $output .= theme('table', $header, $rows);
  if ($form['pager']['#value']) {
    $output .= drupal_render($form['pager']);
  }

  $output .= drupal_render($form);
  $username = isset($_GET['name']) ? $_GET['name'] : '';
  $order = isset($_GET['order']) ? $_GET['order'] : 'Member for';
  $sort = isset($_GET['sort']) ? $_GET['sort'] : 'desc';
  $action_link = '/admin/tcuser/search?rand=' . rand() . '&name=' . $username . '&sort=' . $sort . '&order=' . $order;  
  $form_id = 'tcprofile_search_user_admin';

  return '<form id="' . str_replace('_', '-', $form_id) . '" method="post" accept-charset="UTF-8" action="' . $action_link . '">' . $output . '<input id="edit-' . str_replace('_', '-', $form_id) . '" type="hidden" value="' . $form_id . '" name="form_id" /></form>';
} // function tcprofile_search_render_form

/**
 * confirm form to delete user
 */
function tcprofile_search_user_multiple_delete_confirm(&$form_state) {
  $edit = $form_state['post'];

  $form['accounts'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
  // array_filter() returns only elements with TRUE values.
  foreach (array_filter($edit['accounts']) as $uid => $value) {
    $user = db_result(db_query('SELECT name FROM {users} WHERE uid = %d', $uid));
    $form['accounts'][$uid] = array('#type' => 'hidden', '#value' => $uid, '#prefix' => '<li>', '#suffix' => check_plain($user) ."</li>\n");
  }
  $form['user_operations'] = array('#type' => 'hidden', '#value' => 'delete_confirmed');

  return confirm_form($form,
                      t('Are you sure you want to delete these users?'),
                      'admin/tcuser/search', t('This action cannot be undone.'),
                      t('Delete all'), t('Cancel'));
} // function tcprofile_search_user_multiple_delete_confirm

